<template>
  <div>
    <!-- this is the dic page -->
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/manager' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>字典管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- main-content -->
    <el-card class="course-list">
      <el-button
        type="school"
        icon="el-icon-plus"
        @click="AddDicFormDialog = true"
        style="margin-bottom: 12px;">
        添加数据字典
      </el-button>

      <!-- 添加数据字典表单 -->
      <el-dialog title="添加数据字典"
        :visible.sync="AddDicFormDialog">
        <el-form :model="addForm" class="el-override" label-width="6rem" :rules="addDicRules" ref="addDicForm">
          <el-form-item label="字段名称" prop="name">
            <el-input placeholder="请输入字段名称" v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="出现位置" prop="place">
            <el-input placeholder="请输入出现位置" v-model="addForm.place"></el-input>
          </el-form-item>
          <el-form-item label="英文名称" prop="englishName">
            <el-input placeholder="请输入英文名称" v-model="addForm.englishName"></el-input>
          </el-form-item>
          <el-form-item label="字段内容"
            :rules="{
              required: true, message: '请输入字段内容', trigger: 'blur'
            }">
            <div v-if="dicValues.length > 0">
              <el-row v-for="(value,index) in dicValues" :key="index" class="row-value-form" :gutter="10">
                <el-col :span="18">
                  <el-input placeholder="请输入字段内容" v-model="value.value"></el-input>
                </el-col>
                <el-col :span="2">
                  <i class="el-icon-circle-plus" @click="addValues"></i>
                </el-col>
                <el-col :span="2">
                  <i class="el-icon-remove" @click="removeValues(value,index)"></i>
                </el-col>
              </el-row>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="AddDicFormDialog = false;dicValues = [{ value: '' }];addForm = {name: '', place: '',englishName: ''};">取 消</el-button>
        <el-button type="primary" @click="addDicFormSubmit">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 字典表格 -->
      <el-table
        :data="Dictable"
        class="dic-table"
        border>
        <el-table-column label="字段名" align="center" prop="name"></el-table-column>
        <el-table-column label="字段英文名" align="center" prop="english_name"></el-table-column>
        <el-table-column label="出现位置" align="center" prop="place"></el-table-column>
        <el-table-column label="下拉列表内容" align="center">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
              <span class="el-dropdown-link">
                显示内容<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="(item, index) in scope.row.children" :key="index">{{ item.meaning }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="EditDicForm(scope.row)">编辑</el-button>
            <el-button size="mini" @click="DeleteDicMessage(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 编辑数据字典表单 -->
      <el-dialog title="编辑数据字典"
        :before-close="handleClose"
        :visible.sync="EditDicFormDialog">
        <el-form :model="currentDic" ref="editDicRef" :rules="editDicRules" class="el-override" label-width="6rem">
          <el-form-item label="字段名称" prop="name">
            <el-input placeholder="请输入字段名称" v-model="currentDic.name"></el-input>
          </el-form-item>
          <el-form-item label="出现位置" prop="place">
            <el-input placeholder="请输入出现位置" v-model="currentDic.place"></el-input>
          </el-form-item>
          <el-form-item label="英文名称" prop="english_name">
            <el-input placeholder="请输入英文名称" v-model="currentDic.english_name"></el-input>
          </el-form-item>
          <el-form-item label="字段内容">
            <div v-if="editDicValues.length > 0">
              <el-row v-for="(value,index) in editDicValues" :key="index" class="row-value-form" :gutter="10">
                <el-col :span="18">
                  <el-input placeholder="请输入字段内容" v-model="value.meaning"></el-input>
                </el-col>
                <el-col :span="2">
                  <i class="el-icon-circle-plus" @click="editAddValues"></i>
                </el-col>
                <el-col :span="2">
                  <i class="el-icon-remove" @click="editRemoveValues(value,index)"></i>
                </el-col>
              </el-row>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="EditDicFormDialog = false;editDicValues = [];GetDicList()">取 消</el-button>
          <el-button type="primary" @click="editFormSubmit">确 定</el-button>
        </div>
      </el-dialog>

    <!-- 分页导航 -->
      <el-pagination
        background
        :page-size="10"
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next"
        :total="totalDic">
      </el-pagination>
    </el-card>

  </div>
</template>

<script>
export default {
  data () {
    return {
      // 添加字典的表单验证
      addDicRules: {
        name: [
          { required: true, message: '请输入字段名称', trigger: 'blur' }
        ],
        place: [
          { required: true, message: '请输入出现位置', trigger: 'blur' }
        ],
        englishName: [
          { required: true, message: '请输入英文名称', trigger: 'blur' }
        ]
      },

      // 编辑字典的表单验证
      editDicRules: {
        name: [
          { required: true, message: '请输入字段名称', trigger: 'blur' }
        ],
        place: [
          { required: true, message: '请输入出现位置', trigger: 'blur' }
        ],
        english_name: [
          { required: true, message: '请输入英文名称', trigger: 'blur' }
        ]
      },

      // 页面展示的字典列表
      Dictable: [],
      currentDic: {},
      totalDic: 0,
      AddDicFormDialog: false,
      addForm: {
        name: '',
        place: '',
        englishName: ''
      },
      // 添加的字典值
      dicValues: [{
        value: ''
      }],
      // 进行修改的字典值
      editDicValues: [],
      EditDicFormDialog: false,
      formLabelWidth: '100px',
      // 当前页
      currentPage: 1
    }
  },
  // 执行方法
  created () {
    this.GetDicList()
  },
  methods: {
    // 删除一个字典
    DeleteDicMessage (id) {
      this.$confirm('是否确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.post(`dic/superAdmin/deleteDicList?id=${id}`)
        console.log(res)
        if (!res.state) return this.$message.error(res.msg)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.GetDicList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 获取全部的字典和字典值
    async GetDicList () {
      this.Dictable = []
      const { data: res } = await this.$http.post(`dic/admin/getDicList?page=${this.currentPage - 1}&rows=10`)
      if (!res.state) return this.$message.error(res.msg)
      console.log(res)
      this.totalDic = res.detail.total
      res.detail.list.forEach(async item => {
        var obj = {
          id: '',
          name: '',
          english_name: '',
          place: '',
          children: []
        }
        obj.id = item.id
        obj.name = item.name
        obj.english_name = item.english_name
        obj.place = item.place
        // 接入字段值
        // const { data: resp } = await this.$http.post(`/dic/admin/selectDicListById?id=${item.id}`)
        // 在这里不能使用
        this.$http.post(`/dic/admin/selectDicListById?id=${item.id}`)
          .then(resp => {
            const data = resp.data
            if (!data.state) return this.$message.error(data.msg)
            obj.children = data.detail.dicValue
          })
        this.Dictable.push(obj)
      })
    },
    //
    /// / 增加一个字典及其所有值
    //
    // 向字典表单里面添加一个value值
    addValues () {
      this.dicValues.push({
        value: ''
      })
    },
    // 移除一个value值
    removeValues (value, index) {
      if (value.value !== undefined) {
        if (this.dicValues.length > 1) {
          this.dicValues.splice(index, 1)
        } else {
          this.dicValues = [
            {
              value: ''
            }
          ]
        }
      }
    },
    // 提交一个表单
    addDicFormSubmit () {
      this.$refs.addDicForm.validate(valid => {
        if (!valid) return

        // values代表所有的字典值
        const values = []
        this.dicValues.forEach((item, index) => {
          const obj = {
            meaning: '',
            rankOrder: 0
          }
          obj.meaning = item.value
          obj.rankOrder = index + 1
          // console.log(item + index)
          values.push(obj)
        })
        console.log(values)
        this.$http.post('dic/superAdmin/createDicList', {
          dicList: this.addForm,
          dicValueList: values
        }).then(res => {
          console.log(res)
          this.AddDicFormDialog = false
          this.dicValues = [{
            value: ''
          }]
          this.addForm = {
            name: '',
            place: '',
            englishName: ''
          }
          this.GetDicList()
        })
      })
    },
    //
    /// 编辑一个字典及其所有值
    //
    EditDicForm (dic) {
      this.EditDicFormDialog = true
      this.currentDic = dic
      this.editDicValues = dic.children
    },
    // 删除一个字典值
    editRemoveValues (value, index) {
      if (value.meaning !== undefined) {
        if (this.editDicValues.length > 1) {
          this.editDicValues.splice(index, 1)
        } else {
          this.editDicValues = [
            {
              meaning: ''
            }
          ]
        }
      }
    },
    // 添加一个字典值
    editAddValues () {
      this.editDicValues.push({
        meaning: ''
      })
    },
    // 修改字典表单的提交
    editFormSubmit () {
      this.$refs.editDicRef.validate(valid => {
        if (!valid) return
        const values = []
        this.editDicValues.forEach((item, index) => {
          const obj = {
            meaning: '',
            rankOrder: 0
          }
          // 可能会有value和meaning两种写法，所以直接用||求得其中有值的一个
          obj.meaning = (item.value || item.meaning)
          obj.rankOrder = index + 1
          values.push(obj)
        })
        this.currentDic.englishName = this.currentDic.english_name
        delete this.currentDic.english_name
        // console.log(this.currentDic)
        // console.log(values)
        this.$http.post('dic/superAdmin/updateDicList', {
          dicList: this.currentDic,
          dicValueList: values
        }).then(res => {
          console.log(res)
          const data = res.data
          if (!data.state) return this.$message.error(data.msg)
          this.$message.success(data.msg)
          this.EditDicFormDialog = false
          this.editDicValues = [{
            value: ''
          }]
          this.currentDic = {}
          this.GetDicList()
        })
      })
    },
    // 更改当前页
    handleCurrentChange (page) {
      this.currentPage = page
      this.GetDicList()
    },
    handleClose (done) {
      done()
      this.GetDicList()
    }
  }
}
</script>

<style lang="less" scoped>
.course-list {
  margin-top: 20px;

  .dic-table {

    .el-dropdown-link {
      cursor: pointer;
      color: #27B148;
    }
    .el-icon-arrow-down {
      font-size: 12px;
    }
  }

  .el-pagination {
    margin: 12px 0;
    float: right;
  }
}

.row-value-form {
  width: 100%;
  padding: 0 5px;
  margin-bottom: 12px;
}

</style>
